import  urllib2,urllib
import time,string,random,os

from bs4 import BeautifulSoup



def getPage(url,data=None,timeout=None):
    try:
        r=urllib2.urlopen(url,data,timeout);
        html=r.read();
        return html;
    except Exception as e:
        print e;

def getNowStr(format=None):
    if format=='d':
        return time.strftime("%Y%m%d", time.localtime());
    else:
        return time.strftime("%Y%m%d%H%M%S", time.localtime());
def getRanStr(len):
    return string.join(random.sample('0123456789abcdefhjk',len)).replace(" ","");
suffixes=["jpg","jpeg","gif","png","bmp"]
def getSuffix(str):
    if str==None:
        return '.jpg'
    arr = str.split('.')
    r=arr[len(arr) - 1]
    if r in suffixes:
        return '.%s'%r
    else:
        return  '.jpg'


def initDir(lastdir=None):
    if lastdir==None:
        lastdir=getRanStr(5);
    p=os.path.join(baseDir,getNowStr('d'),lastdir)
    if os.path.exists(p):
        return p;
    os.makedirs(p)
    return p;
def downLoad(url,downdir,lastdir=None):
    if url=='' or url==None:
        return ;
    print "xiazai%s" %url
    x= os.path.join(downdir,'%s%s%s'%(getNowStr(),getRanStr(3),getSuffix(url)))
    print x
    urllib.urlretrieve(url,x)

def downLoanAll(url):
    html = getPage(url)
    soup = BeautifulSoup(html)
    downd=initDir();
    for aa in soup.find_all('img'):
        #    #print aa
        downLoad(aa.get('src'),downd);

baseDir="E:\data";
#print initDir('14b05');
url="http://dp.pconline.com.cn/photo/4838090_3.html";
downLoanAll(url);
#print downLoad('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1519362138077&di=b81379523d8fe7e89e2e004595c8b3c0&imgtype=0&src=http%3A%2F%2Fpic.yesky.com%2FuploadImages%2F2015%2F137%2F41%2F26R59SSX6287.jpg');
#print getRanStr(5)
#print getNowStr();
#print getNowStr('d')

#print html;